package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.ApiConstant;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrdersService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

import static com.sky.constant.ApiConstant.BD_GET_DISTANCE_API;

/**
 * @Author : xiongke
 * @Description:
 * @Date: 2024/8/30
 */
@Service
@Slf4j
public class OrdersServiceImpl implements OrdersService {

    @Resource
    AddressBookMapper addressBookMapper;
    @Resource
    ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Resource
    WeChatPayUtil weChatPayUtil;
    @Resource
    UserMapper userMapper;
    //获取商家地址与百度ak
    @Value("${sky.shop.address}")
    private String shopAddress;
    @Value("${sky.baidu.ak}")
    private String AK;
    @Autowired
    private WebSocketServer webSocketServer;

    /*
    * 获取经纬度
    * */
    private String getLocation(String address){
        // 组装参数
        HashMap<String, String> map = new HashMap<>();
        map.put("address",address);
        map.put("ak",AK);
        map.put("output","json");

        String json = HttpClientUtil.doGet(ApiConstant.BD_API, map);
        JSONObject jsonObject = JSON.parseObject(json);
        String status = jsonObject.getString("status");
        if (!status.equals("0")){
            throw new AddressBookBusinessException("百度接口地址解析失败。");
        }
        //获取到经纬度
        String result = jsonObject.getString("result");
        JSONObject resultObject = JSON.parseObject(result);
        String location = resultObject.getString("location");
        JSONObject locationObject = JSON.parseObject(location);
        String lat = locationObject.getString("lat");//纬度
        String lng = locationObject.getString("lng");//经度
        String response = lat + "," + lng;
        log.info("店铺的经纬度：{}", response);
        return response;
    }

    /*
    * 获取两地之间的距离
    * */
    private String getDistance(String origin, String destination) {
        log.info("计算：{}到{}的距离",origin,destination);
        //构造参数
        HashMap<String, String> map = new HashMap<>();
        map.put("origin",origin);
        map.put("destination",destination);
        map.put("ak",AK);
        String json = HttpClientUtil.doGet(BD_GET_DISTANCE_API, map);
        JSONObject jsonObject = JSON.parseObject(json);
        String status = jsonObject.getString("status");
        if (!status.equals("0")){
            throw new AddressBookBusinessException("传入参数有误");
        }
        String result = jsonObject.getString("result");
        JSONObject resultObject = JSON.parseObject(result);
        String routes = resultObject.getString("routes");

        JSONArray routesObjects = JSON.parseArray(routes);
        JSONObject routesObject = routesObjects.getJSONObject(0);
        String distance = routesObject.getString("distance");
        log.info("distance:{}",distance);
        return distance;
    }

    //校验位置
    private void checkOutOfRange(String address){
        //获取经纬度
        String shopLocation = getLocation(shopAddress);
        //获取到用户地址的经纬度
        String userLocation = getLocation(address);
        //计算距离
       String distance = getDistance(shopLocation,userLocation);
       if (Integer.parseInt(distance) > 6000){
           throw new AddressBookBusinessException("超出配送范围");
       }
    }




    @Override
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO dto) {
        //判断地址是否存在
        AddressBook addressBook = addressBookMapper.getById(dto.getAddressBookId());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //判断购物车是否为空
        Long userId = BaseContext.getCurrentId();
        List<ShoppingCart> shoppinglist = shoppingCartMapper.list(userId);
        if (shoppinglist == null) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        checkOutOfRange(addressBook.getProvinceName()+addressBook.getCityName()+addressBook.getDistrictName()+addressBook.getDetail());
        //加入订单表
        Orders orders = Orders.builder()
                .number(String.valueOf(System.currentTimeMillis()))
                .status(Orders.PENDING_PAYMENT)
                .userId(userId)
                .orderTime(LocalDateTime.now())
                .payStatus(Orders.UN_PAID)
                .phone(addressBook.getPhone())
                .address(addressBook.getDetail())
                .consignee(addressBook.getConsignee())
                .build();
        BeanUtils.copyProperties(dto, orders);
        ordersMapper.save(orders);
        //加入订单详情表
        ArrayList<OrderDetail> orderDetails = new ArrayList<>();
        for (ShoppingCart shoppingCart : shoppinglist) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orders.getId());
            BeanUtils.copyProperties(shoppingCart, orderDetail);
            orderDetails.add(orderDetail);
        }
        //批量添加
        orderDetailMapper.insertBatch(orderDetails);
        //清空购物车
        shoppingCartMapper.delByUserId(userId);
        return OrderSubmitVO.builder()
                .orderAmount(orders.getAmount())
                .orderNumber(orders.getNumber())
                .orderTime(orders.getOrderTime())
                .id(orders.getId())
                .build();
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = ordersMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        ordersMapper.update(orders);
        //使用websocket像管理端推送消息
        HashMap<String, Object> map = new HashMap<>();
        map.put("type", 1); // 类型1为来单提醒 2为催单
        map.put("orderId" , ordersDB.getId());
        map.put("content" , "订单号为："+ordersDB.getId());
        // 转为json字符串
        String jsonString = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(jsonString);

    }

    @Override
    public OrderVO orderDetail(Long id) {
        OrderVO orderVO = new OrderVO();
        Orders order = ordersMapper.getById(id);
        BeanUtils.copyProperties(order, orderVO);
        List<OrderDetail> orderDetailList = orderDetailMapper.selectByOrderId(id);
        orderVO.setOrderDetailList(orderDetailList);
        return orderVO;
    }

    @Override
    public void cancelOrder(Long id) {
        ordersMapper.cancelOrder(id, Orders.CANCELLED);
    }

    @Override
    public void cancelOrder(OrdersCancelDTO dto) {
        Orders order = Orders.builder().id(dto.getId()).status(Orders.CANCELLED).cancelReason(dto.getCancelReason()).build();
        ordersMapper.update(order);
    }

    @Override
    public PageResult queryPage(OrdersPageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        Long userId = BaseContext.getCurrentId();
        if (userId != 1) {
            dto.setUserId(userId);
        }
        Page<OrderVO> page = ordersMapper.queryByPage(dto);
        //组装vo
        List<OrderVO> list = new ArrayList();
        if (page != null && page.getTotal() > 0) {
            for (OrderVO orders : page) {
                Long orderId = orders.getId();// 订单id
                // 查询订单明细
                List<OrderDetail> orderDetails = orderDetailMapper.selectByOrderId(orderId);
                orders.setOrderDetailList(orderDetails);
                String orderDishes = getOrderDishesStr(orders);
                orders.setOrderDishes(orderDishes);
                list.add(orders);
            }
        }
        return new PageResult(page.getTotal(), list);

    }

    /**
     * 根据订单id获取菜品信息字符串
     *
     * @param orders
     * @return
     */
    private String getOrderDishesStr(Orders orders) {
        // 查询订单菜品详情信息（订单中的菜品和数量）
        List<OrderDetail> orderDetailList = orderDetailMapper.selectByOrderId(orders.getId());

        // 将每一条订单菜品信息拼接为字符串（格式：宫保鸡丁*3；）
        List<String> orderDishList = orderDetailList.stream().map(x -> {
            String orderDish = x.getName() + "*" + x.getNumber() + ";";
            return orderDish;
        }).collect(Collectors.toList());

        // 将该订单对应的所有菜品信息拼接在一起
        return String.join("", orderDishList);
    }


    @Override
    @Transactional
    public void repetition(Long id) {
        //清除购物车
        shoppingCartMapper.delByUserId(BaseContext.getCurrentId());
        // 再来一单直接加入购物车
        List<OrderDetail> orderDetailList = orderDetailMapper.selectByOrderId(id);
        List<ShoppingCart> shoppingCartList = new ArrayList<>();
        for (OrderDetail orderDetail : orderDetailList) {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail, shoppingCart);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCart.setNumber(1);
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCartList.add(shoppingCart);
        }
        shoppingCartMapper.insertBatch(shoppingCartList);

    }

    @Override
    public OrderStatisticsVO statistics() {
        OrderStatisticsVO result = orderDetailMapper.queryStatistics();
        return result;
    }


    /*
     * 完成订单
     * */
    @Override
    public void complete(Long id) {
        Orders order = Orders.builder().id(id).status(Orders.COMPLETED).deliveryTime(LocalDateTime.now()).build();
        ordersMapper.update(order);
    }

    /*
     * 接单
     * */
    @Override
    public void confirmOrder(OrdersConfirmDTO dto) {
        Orders order = Orders.builder().status(Orders.CONFIRMED).id(dto.getId()).build();
        ordersMapper.update(order);
    }

    /*
     * 派送
     * */

    @Override
    public void deliver(Long id) {
        Orders order = Orders.builder().status(Orders.DELIVERY_IN_PROGRESS).id(id).build();
        ordersMapper.update(order);
    }

    @Override
    public void rejection(OrdersRejectionDTO dto) {
        //判断订单是否存在且订单在接单后不能拒绝
        Orders order = ordersMapper.getById(dto.getId());
        if (ObjectUtils.isEmpty(order)) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        if (order.getStatus() != Orders.TO_BE_CONFIRMED) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders updateOrder = Orders.builder()
                .id(dto.getId())
                .status(Orders.CANCELLED)
                .rejectionReason(dto.getRejectionReason())
                .cancelTime(LocalDateTime.now())
                .build();
        //判断支付状态
        if (order.getPayStatus() == Orders.PAID){
            // 调用微信支付接口退款

            // 退款成功后微信回调我们接口 修改订单状态 此处直接一起修改
            updateOrder.setPayStatus(Orders.REFUND);
        }
        ordersMapper.update(updateOrder);
    }

    @Override
    public void reminder(Long id) {
        if (id == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        // 组装websocket需要的参数
        HashMap<Object, Object> map = new HashMap<>();
        map.put("type", 2);
        map.put("orderId" , id);
        map.put("content" , "订单号为："+id);
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }
}
